package com.zyq.controller;

import com.zyq.constant.Constant;
import com.zyq.entity.SysUser;
import com.zyq.service.IUserService;
import com.zyq.util.JwtUtil;
import com.zyq.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public abstract class BaseController {

    public final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected IUserService userService;

    /**
     * 获取 token
     * @return
     */
    protected String getToken(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader(Constant.User.ACCESS_TOKEN);
    }

    /**
     * 从 accessToken 中获取 userId
     * @param token
     * @return
     */
    protected String getUserId(String token){
        /*Object userId = JwtUtil.getValue(token,JwtUtil.fnToFieldName(SysUser::getId));// 操作人
        if (userId != null){
            return String.valueOf(userId);
        }*/
        return String.valueOf(JwtUtil.getValue(token,JwtUtil.fnToFieldName(SysUser::getId)));
    }

    /**
     * 获取登录账户userId
     * @return
     */
    protected String getUserId(){
        return getLoginUser().getId();
    }

    /**
     * 获取登录账户username
     * @return
     */
    protected String getUsername(String token){
        return String.valueOf(JwtUtil.getValue(token,JwtUtil.fnToFieldName(SysUser::getUsername)));
    }

    /**
     * 获取登录账户username
     * @return
     */
    protected String getUsername(){
        return getLoginUser().getUsername();
    }

    /**
     * 获取当前登录用户，也可以获取token中的用户
     * @return
     */
    protected SysUser getLoginUser(){
//        return (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = getUsername(getToken());
        String userKey = Constant.User.USER_KEY + username;
        return RedisUtil.getByCache(userKey, Constant.User.USER_KEY_EXPIRE, SysUser.class, () -> userService.getUserByUserName(username));
    }
}
